using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.FileProviders;
using System.IO;
using System.Threading.Tasks;
using System.Text;
using System.Text.Json;
using FinData.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using MySql.Data.MySqlClient;
using System.Net.Http;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Text.Encodings.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using MongoDB.Bson;
using MongoDB.Driver;

// 注册编码提供程序
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
builder.Services.AddControllersWithViews();

// 添加会话服务
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// 添加数据库服务
builder.Services.AddSingleton<DatabaseService>();

// 添加交易日历服务
builder.Services.AddSingleton<TradingCalendarService>();

// 添加MongoDB服务
builder.Services.AddSingleton<MongoService>();

// 添加论坛服务
builder.Services.AddSingleton<ForumService>();

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins",
        builder => builder
            .WithOrigins("http://localhost:8000")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
});

// 添加对DELETE等HTTP方法的支持
builder.Services.AddRouting(options => options.LowercaseUrls = true);

// 添加HttpClient服务用于调用Python API
builder.Services.AddHttpClient();

var app = builder.Build();

// 获取数据库服务实例
var dbService = app.Services.GetRequiredService<DatabaseService>();
var calendarService = app.Services.GetRequiredService<TradingCalendarService>();
var mongoService = app.Services.GetRequiredService<MongoService>();

// 输出当前环境
Console.WriteLine($"当前环境: {app.Environment.EnvironmentName}");
Console.WriteLine("应用程序启动中...");

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/error");
    app.UseHsts();
}

// 使用CORS中间件
app.UseCors("AllowSpecificOrigins");

// 使用会话中间件
app.UseSession();

// 静态文件服务
app.UseStaticFiles();

// 添加对templates目录的访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "templates")),
    RequestPath = "/templates"
});

// 添加对static目录的访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "static")),
    RequestPath = "/static"
});

// 添加对wwwroot/static目录的访问 - 确保两处的static都能被访问到
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "static")),
    RequestPath = "/static"
});

// 注释掉这个配置，避免路径混淆
// app.UseStaticFiles(new StaticFileOptions
// {
//     FileProvider = new PhysicalFileProvider(
//         Path.Combine(Directory.GetCurrentDirectory(), "static", "uploads")),
//     RequestPath = "/uploads"
// });

// 添加对交易日历CSV文件的访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Directory.GetCurrentDirectory()),
    RequestPath = ""
});

app.UseRouting();

// 添加终结点映射
app.UseEndpoints(endpoints =>
{
    // 用户信息API
    endpoints.MapGet("/api/user-info", async context =>
    {
        try
        {
            // 获取用户ID
            int? userId = context.Session.GetInt32("UserId");
            if (userId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "用户未登录" });
                return;
            }

            // 获取数据库服务
            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取用户信息
            var userInfo = await dbService.GetUserInfoAsync(userId.Value);
            if (userInfo != null)
            {
                // 返回用户信息
                context.Response.ContentType = "application/json; charset=utf-8";
                await context.Response.WriteAsJsonAsync(userInfo);
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { detail = "用户信息不存在" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户信息API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 登录API
    endpoints.MapPost("/api/login", async context =>
    {
        try
        {
            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            var forumService = context.RequestServices.GetRequiredService<ForumService>();
            
            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string username = form["username"];
            string password = form["password"];

            // 验证参数
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名和密码不能为空" });
                return;
            }

            // 验证用户
            int userId = await dbService.ValidateUserAsync(username, password);
            if (userId > 0)
            {
                // 检查用户是否被封禁
                var punishmentStatus = await forumService.CheckUserPunishmentStatusAsync(userId);
                if (punishmentStatus.IsBanned)
                {
                    // 用户已被封禁，返回错误信息
                    context.Response.StatusCode = 403;
                    await context.Response.WriteAsJsonAsync(new { 
                        detail = "您的账户已被封禁，无法登录。",
                        reason = punishmentStatus.BanReason,
                        isBanned = true
                    });
                    return;
                }
                
                // 登录成功，设置会话
                context.Session.SetInt32("UserId", userId);
                context.Session.SetString("Username", username);

                // 获取用户角色
                var userInfo = await dbService.GetUserInfoAsync(userId);
                if (userInfo != null && !string.IsNullOrEmpty(userInfo.Role))
                {
                    context.Session.SetString("UserRole", userInfo.Role);
                }
                else
                {
                    context.Session.SetString("UserRole", "user"); // 默认角色
                }

                // 返回成功响应
                await context.Response.WriteAsJsonAsync(new { 
                    message = "登录成功", 
                    redirect = "/dashboard" 
                });
            }
            else
            {
                // 登录失败
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名或密码错误" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"登录API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 注册API
    endpoints.MapPost("/api/register", async context =>
    {
        try
        {
            var dbService = context.RequestServices.GetRequiredService<DatabaseService>();
            
            // 获取表单数据
            var form = await context.Request.ReadFormAsync();
            string username = form["username"];
            string password = form["password"];
            string securityAnswer = form["security_answer"];

            // 验证参数
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(securityAnswer))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "所有字段都不能为空" });
                return;
            }

            // 验证用户名格式（6个字符以上，只支持字母和数字）
            if (!Regex.IsMatch(username, @"^[A-Za-z0-9]{6,}$"))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名必须6个字符以上，只支持字母和数字" });
                return;
            }

            // 验证密码格式（8个字符以上，支持字母、数字及下划线_）
            if (!Regex.IsMatch(password, @"^[A-Za-z0-9_]{8,}$"))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "密码必须8个字符以上，支持字母、数字及下划线_" });
                return;
            }

            // 验证安全问题答案（只能输入中文）
            if (!Regex.IsMatch(securityAnswer, @"^[\u4e00-\u9fa5]+$"))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "安全问题答案只能输入中文" });
                return;
            }

            // 注册用户
            bool success = await dbService.RegisterUserAsync(username, password, securityAnswer);
            if (success)
            {
                // 注册成功
                context.Response.StatusCode = 201;
                await context.Response.WriteAsJsonAsync(new { message = "注册成功，请登录" });
            }
            else
            {
                // 注册失败
                context.Response.StatusCode = 400;
                await context.Response.WriteAsJsonAsync(new { detail = "用户名已存在" });
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"注册API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });

    // 注销API
    endpoints.MapPost("/api/logout", async context =>
    {
        try
        {
            // 清除会话
            context.Session.Clear();

            // 返回成功响应
            await context.Response.WriteAsJsonAsync(new { message = "注销成功" });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"注销API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
    
    // 使用控制器端点
    endpoints.MapControllers();

    // 检查用户禁言状态API
    endpoints.MapGet("/api/check-mute-status", async context =>
    {
        try
        {
            // 检查用户是否已登录
            var userId = context.Session.GetInt32("UserId");
            if (userId == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsJsonAsync(new { detail = "未登录" });
                return;
            }

            var forumService = context.RequestServices.GetRequiredService<ForumService>();
            
            // 检查用户是否被禁言
            var punishmentStatus = await forumService.CheckUserPunishmentStatusAsync(userId.Value);
            
            if (punishmentStatus.IsMuted)
            {
                // 用户已被禁言，返回禁言信息
                context.Response.StatusCode = 403;
                await context.Response.WriteAsJsonAsync(new { 
                    detail = "您的账户已被禁言，无法发言。",
                    reason = punishmentStatus.MuteReason,
                    isMuted = true
                });
                return;
            }
            
            // 用户未被禁言
            await context.Response.WriteAsJsonAsync(new { isMuted = false });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"检查禁言状态API异常: {ex.Message}");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { detail = "服务器内部错误，请稍后再试" });
        }
    });
});

// 启用控制器端点路由
app.MapControllers();

// 初始化服务
Console.WriteLine("开始初始化服务...");

bool dbInitialized = false;
bool calendarInitialized = false;

// 初始化数据库
try
{
    Console.WriteLine("开始初始化数据库...");
    dbService.InitializeDatabaseAsync().GetAwaiter().GetResult();
    
    // 检查users表是否有role字段
    using (var connection = new MySqlConnection("Server=localhost;Port=3306;Database=findata;User=root;Password=root;"))
    {
        connection.Open();
        bool hasRoleColumn = false;
        
        using (var cmd = new MySqlCommand(
            "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'findata' AND TABLE_NAME = 'users' AND COLUMN_NAME = 'role'", 
            connection))
        {
            var result = cmd.ExecuteScalar();
            hasRoleColumn = Convert.ToInt32(result) > 0;
        }
        
        if (!hasRoleColumn)
        {
            Console.WriteLine("添加role字段到users表...");
            using (var cmd = new MySqlCommand(
                "ALTER TABLE users ADD COLUMN role VARCHAR(20) DEFAULT 'user'", 
                connection))
            {
                cmd.ExecuteNonQuery();
                Console.WriteLine("role字段添加成功");
            }
        }
        else
        {
            Console.WriteLine("users表已有role字段");
        }
    }
    
    Console.WriteLine("数据库初始化完成");
    dbInitialized = true;
}
catch (Exception ex)
{
    Console.WriteLine($"数据库初始化失败: {ex.Message}");
    // 不会中断应用程序启动，但会标记数据库未初始化
}

// 初始化交易日历
try
{
    Console.WriteLine("开始初始化交易日历...");
    calendarService.Initialize();
    Console.WriteLine("交易日历初始化完成");
    calendarInitialized = true;
}
catch (Exception ex)
{
    Console.WriteLine($"交易日历初始化失败: {ex.Message}");
    // 不会中断应用程序启动，但会标记交易日历未初始化
}

// 输出初始化状态
Console.WriteLine($"服务初始化状态: 数据库={dbInitialized}, 交易日历={calendarInitialized}");
if (!dbInitialized)
{
    Console.WriteLine("警告: 数据库未初始化，用户注册和登录功能可能不可用");
    Console.WriteLine("警告: 论坛功能可能不可用，需要初始化数据库");
}
if (!calendarInitialized)
{
    Console.WriteLine("警告: 交易日历未初始化，交易日判断功能可能不可用");
}

// 确保必要的目录存在
try
{
    Console.WriteLine("开始检查并创建必要的目录...");
    
    // 创建static目录
    string staticDir = Path.Combine(Directory.GetCurrentDirectory(), "static");
    if (!Directory.Exists(staticDir))
    {
        Directory.CreateDirectory(staticDir);
        Console.WriteLine($"已创建static目录: {staticDir}");
    }
    else
    {
        Console.WriteLine($"static目录已存在: {staticDir}");
    }
    
    // 创建uploads目录
    string uploadsDir = Path.Combine(staticDir, "uploads");
    if (!Directory.Exists(uploadsDir))
    {
        Directory.CreateDirectory(uploadsDir);
        Console.WriteLine($"已创建uploads目录: {uploadsDir}");
    }
    else
    {
        Console.WriteLine($"uploads目录已存在: {uploadsDir}");
    }
    
    // 创建forum目录
    string forumDir = Path.Combine(uploadsDir, "forum");
    if (!Directory.Exists(forumDir))
    {
        Directory.CreateDirectory(forumDir);
        Console.WriteLine($"已创建forum目录: {forumDir}");
    }
    else
    {
        Console.WriteLine($"forum目录已存在: {forumDir}");
    }
    
    // 测试写入权限
    string testFile = Path.Combine(forumDir, "startup_test.txt");
    File.WriteAllText(testFile, "应用程序启动测试");
    Console.WriteLine($"已创建测试文件: {testFile}");
    
    Console.WriteLine("目录检查和创建完成");
}
catch (Exception ex)
{
    Console.WriteLine($"创建目录时出错: {ex.Message}");
    Console.WriteLine($"异常类型: {ex.GetType().Name}");
    Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
}

// 设置路由
app.MapGet("/", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") != null)
        {
            // 已登录，重定向到dashboard
            context.Response.Redirect("/dashboard");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/dark-welcome.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving welcome page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

app.MapGet("/blank", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") != null)
        {
            // 已登录，重定向到dashboard
            context.Response.Redirect("/dashboard");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/blank.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving blank page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

app.MapGet("/login", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") != null)
        {
            // 已登录，重定向到dashboard
            context.Response.Redirect("/dashboard");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/login.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving login page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

app.MapGet("/register", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") != null)
        {
            // 已登录，重定向到dashboard
            context.Response.Redirect("/dashboard");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/register.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving register page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

app.MapGet("/dashboard", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") == null)
        {
            // 未登录，重定向到登录页
            context.Response.Redirect("/login");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/dashboard.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving dashboard page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

app.MapGet("/favorites", async context =>
{
    try
    {
        // 不检查用户是否已登录，允许所有用户访问
        string htmlContent = await File.ReadAllTextAsync("templates/favorites.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving favorites page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 回测页面路由
app.MapGet("/backtest", async context =>
{
    try
    {
        // 检查用户是否已登录
        int? userId = context.Session.GetInt32("UserId");
        string? username = context.Session.GetString("Username");
        
        if (userId == null || string.IsNullOrEmpty(username))
        {
            // 未登录，重定向到登录页面
            context.Response.Redirect("/login");
            return;
        }

        // 可以选择显示回测页面或直接重定向到回测平台
        if (context.Request.Query.ContainsKey("redirect") && context.Request.Query["redirect"] == "true")
        {
            // 直接重定向到回测平台，添加用户ID参数
            context.Response.Redirect($"http://localhost:8080/factor/?user_id={userId}");
            return;
        }

        // 用户已登录，显示回测页面
        string htmlContent = await File.ReadAllTextAsync("templates/backtest.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving backtest page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 忘记密码页面
app.MapGet("/forgot-password", async context =>
{
    try
    {
        string htmlContent = await File.ReadAllTextAsync("templates/forgot_password.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving forgot password page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 数据页面路由
app.MapGet("/data", async context =>
{
    try {
        // 返回数据页面
        string htmlContent = await File.ReadAllTextAsync("templates/data.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving data page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 论坛页面路由
app.MapGet("/forum", async context =>
{
    try {
        // 返回论坛列表页面
        string htmlContent = await File.ReadAllTextAsync("templates/forum_list.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving forum page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 添加论坛创建帖子页面路由
app.MapGet("/forum/create", async context =>
{
    try
    {
        // 检查用户是否已登录
        if (context.Session.GetInt32("UserId") == null)
        {
            // 未登录，重定向到登录页面
            context.Response.Redirect("/login");
            return;
        }

        string htmlContent = await File.ReadAllTextAsync("templates/forum_create.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving forum create page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 论坛帖子详情页面路由
app.MapGet("/forum/post/{id}", async context =>
{
    try
    {
        string htmlContent = await File.ReadAllTextAsync("templates/forum_post.html", Encoding.UTF8);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving forum post page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// 论坛API：获取帖子列表
app.MapGet("/api/forum/posts", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取页码参数
        int page = 1;
        if (context.Request.Query.ContainsKey("page"))
        {
            int.TryParse(context.Request.Query["page"], out page);
            if (page < 1) page = 1;
        }

        // 获取页大小参数
        int pageSize = 10;
        if (context.Request.Query.ContainsKey("pageSize"))
        {
            int.TryParse(context.Request.Query["pageSize"], out pageSize);
            if (pageSize < 1 || pageSize > 50) pageSize = 10;
        }
        
        // 获取排序方式
        string sortBy = "newest";
        if (context.Request.Query.ContainsKey("sortBy"))
        {
            sortBy = context.Request.Query["sortBy"].ToString();
            // 验证排序方式是否有效
            if (!new[] { "newest", "likes", "comments", "views", "hot" }.Contains(sortBy))
            {
                sortBy = "newest"; // 默认排序方式
            }
        }

        // 获取帖子列表
        var posts = await forumService.GetPostsAsync(page, pageSize, sortBy);
        
        // 获取总帖子数用于分页
        int totalPosts = await forumService.GetPostCountAsync();
        int totalPages = (int)Math.Ceiling(totalPosts / (double)pageSize);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { 
            posts, 
            pagination = new {
                currentPage = page,
                pageSize,
                totalPosts,
                totalPages
            }
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取帖子列表API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取帖子列表失败" });
    }
});

// 论坛API：获取热门帖子
app.MapGet("/api/forum/hot-posts", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取数量参数
        int count = 5;
        if (context.Request.Query.ContainsKey("count"))
        {
            int.TryParse(context.Request.Query["count"], out count);
            if (count < 1 || count > 10) count = 5;
        }

        // 获取热门帖子
        var posts = await forumService.GetHotPostsAsync(count);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(posts);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取热门帖子API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取热门帖子失败" });
    }
});

// 论坛API：获取帖子详情
app.MapGet("/api/forum/posts/{id}", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 获取当前用户ID（如果已登录）
        int? userId = context.Session.GetInt32("UserId");

        // 获取帖子详情
        var post = await forumService.GetPostByIdAsync(postId, userId);

        if (post == null)
        {
            context.Response.StatusCode = 404;
            await context.Response.WriteAsJsonAsync(new { error = "帖子不存在" });
            return;
        }

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(post);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取帖子详情API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取帖子详情失败" });
    }
});

// 论坛API：获取帖子标签
app.MapGet("/api/forum/posts/{id}/tags", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 获取帖子标签
        var tags = await forumService.GetPostTagsAsync(postId);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(tags);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取帖子标签API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取帖子标签失败" });
    }
});

// 论坛API：获取帖子评论
app.MapGet("/api/forum/posts/{id}/comments", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 获取评论列表
        var comments = await forumService.GetCommentsAsync(postId);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(comments);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取评论列表API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取评论列表失败" });
    }
});

// 论坛API：创建帖子
app.MapPost("/api/forum/posts", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 解析请求体
        var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        var data = JsonSerializer.Deserialize<Dictionary<string, string>>(requestBody, options);

        // 验证参数
        if (data == null || !data.ContainsKey("title") || !data.ContainsKey("content") || 
            string.IsNullOrEmpty(data["title"]) || string.IsNullOrEmpty(data["content"]))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "标题和内容不能为空" });
            return;
        }

        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        
        // 创建帖子
        int postId = await forumService.CreatePostAsync(data["title"], data["content"], userId);

        // 返回结果
        context.Response.StatusCode = 201;
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { 
            id = postId,
            message = "帖子创建成功"
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"创建帖子API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "创建帖子失败" });
    }
});

// 论坛API：添加评论
app.MapPost("/api/forum/posts/{id}/comments", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        if (userId == null)
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "请先登录" });
            return;
        }

        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 解析请求体
        var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        var data = JsonSerializer.Deserialize<Dictionary<string, string>>(requestBody, options);

        // 验证参数
        if (data == null || !data.ContainsKey("content") || string.IsNullOrEmpty(data["content"]))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "评论内容不能为空" });
            return;
        }

        // 添加评论
        int commentId = await forumService.AddCommentAsync(postId, userId.Value, data["content"]);

        // 返回结果
        context.Response.StatusCode = 201;
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { 
            id = commentId,
            message = "评论添加成功"
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"添加评论API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "添加评论失败" });
    }
});

// 论坛API：获取点赞状态
app.MapGet("/api/forum/posts/{id}/like-status", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        if (userId == null)
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "请先登录" });
            return;
        }

        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 检查是否已点赞
        bool isLiked = await forumService.IsLikedAsync(postId, userId.Value);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { isLiked });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取点赞状态API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取点赞状态失败" });
    }
});

// 论坛API：点赞或取消点赞
app.MapPost("/api/forum/posts/{id}/like", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        if (userId == null)
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "请先登录" });
            return;
        }

        // 获取帖子ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int postId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID" });
            return;
        }

        // 点赞或取消点赞
        bool isLiked = await forumService.ToggleLikeAsync(postId, userId.Value);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { isLiked });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"点赞API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "点赞操作失败" });
    }
});

// 论坛API：举报帖子
app.MapPost("/api/forum/report", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        if (userId == null)
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "请先登录" });
            Console.WriteLine("举报失败: 用户未登录");
            return;
        }

        Console.WriteLine($"开始处理举报请求 - 用户ID: {userId}");

        // 读取请求体
        string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
        Console.WriteLine($"请求体: {requestBody}");
        
        try
        {
            // 直接使用JsonDocument解析，避免类型转换问题
            using (JsonDocument doc = JsonDocument.Parse(requestBody))
            {
                JsonElement root = doc.RootElement;
                
                // 验证必要参数是否存在
                if (!root.TryGetProperty("postId", out JsonElement postIdElement) || 
                    !root.TryGetProperty("reason", out JsonElement reasonElement))
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsJsonAsync(new { error = "参数不完整" });
                    Console.WriteLine("举报失败: 参数不完整");
                    return;
                }
                
                // 解析postId，无论它是字符串还是数字
                int postId;
                if (postIdElement.ValueKind == JsonValueKind.Number)
                {
                    postId = postIdElement.GetInt32();
                    Console.WriteLine($"从JSON数字直接获取postId: {postId}");
                }
                else if (postIdElement.ValueKind == JsonValueKind.String)
                {
                    string postIdStr = postIdElement.GetString() ?? "";
                    if (!int.TryParse(postIdStr, out postId))
                    {
                        context.Response.StatusCode = 400;
                        await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID格式" });
                        Console.WriteLine($"无法将字符串 \"{postIdStr}\" 转换为整数");
                        return;
                    }
                    Console.WriteLine($"从JSON字符串解析postId: {postId}");
                }
                else
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsJsonAsync(new { error = "无效的帖子ID格式" });
                    Console.WriteLine($"postId的JSON类型不支持: {postIdElement.ValueKind}");
                    return;
                }
                
                // 获取举报原因
                string reason = reasonElement.ValueKind == JsonValueKind.String 
                    ? reasonElement.GetString() ?? "" 
                    : reasonElement.ToString();
                
                // 获取详情（如果存在）
                string detail = "";
                if (root.TryGetProperty("detail", out JsonElement detailElement) && 
                    detailElement.ValueKind == JsonValueKind.String)
                {
                    detail = detailElement.GetString() ?? "";
                }
                
                Console.WriteLine($"准备记录举报 - 帖子ID: {postId}, 原因: {reason}, 详情长度: {detail.Length}");
                
                // 记录举报
                int reportId = await forumService.ReportPostAsync(postId, userId.Value, reason, detail);
                Console.WriteLine($"举报记录成功 - 举报ID: {reportId}");
                
                // 返回成功结果
                context.Response.StatusCode = 201;
                context.Response.ContentType = "application/json; charset=utf-8";
                await context.Response.WriteAsJsonAsync(new { message = "举报已提交", reportId = reportId });
            }
        }
        catch (JsonException jsonEx)
        {
            Console.WriteLine($"JSON解析失败: {jsonEx.Message}");
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的JSON格式" });
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"举报帖子API异常: {ex.Message}");
        Console.WriteLine($"异常堆栈: {ex.StackTrace}");
        if (ex.InnerException != null)
        {
            Console.WriteLine($"内部异常: {ex.InnerException.Message}");
        }
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "举报提交失败", message = ex.Message });
    }
});

// 论坛API：搜索帖子
app.MapGet("/api/forum/search", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取搜索关键词
        string keyword = context.Request.Query["keyword"];
        if (string.IsNullOrWhiteSpace(keyword))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "搜索关键词不能为空" });
            return;
        }

        // 使用高级搜索功能
        var searchResults = await forumService.AdvancedSearchAsync(keyword);
        
        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { 
            titleMatches = searchResults["title"], 
            tagMatches = searchResults["tag"], 
            contentMatches = searchResults["content"] 
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"搜索帖子API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "搜索失败" });
    }
});

// 论坛API：获取论坛统计数据
app.MapGet("/api/forum/stats", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取统计数据
        var stats = await forumService.GetForumStatsAsync();

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(stats);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取论坛统计API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取统计数据失败" });
    }
});

// 论坛API：按标签搜索帖子（API端点）
app.MapGet("/api/forum/search/tag/{tag}", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取标签
        var tag = context.Request.RouteValues["tag"]?.ToString();
        if (string.IsNullOrWhiteSpace(tag))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "标签不能为空" });
            return;
        }

        // 搜索帖子
        var posts = await forumService.SearchPostsByTagAsync(tag);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(posts);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"按标签搜索帖子API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "按标签搜索帖子失败" });
    }
});

// 论坛API：获取热门标签
app.MapGet("/api/forum/hot-tags", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 获取数量参数
        int count = 5;
        if (context.Request.Query.ContainsKey("count"))
        {
            int.TryParse(context.Request.Query["count"], out count);
            if (count < 1 || count > 20) count = 5;
        }

        // 获取热门标签
        var tags = await forumService.GetHotTagsAsync(count);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(tags);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取热门标签API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取热门标签失败" });
    }
});

// 论坛API：创建带标签的帖子
app.MapPost("/api/forum/posts-with-tags", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 解析请求体
        var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        var data = JsonSerializer.Deserialize<JsonElement>(requestBody);

        // 验证参数
        if (!data.TryGetProperty("title", out var titleElement) || 
            !data.TryGetProperty("content", out var contentElement))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "标题和内容不能为空" });
            return;
        }

        string title = titleElement.GetString() ?? "";
        string content = contentElement.GetString() ?? "";

        if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(content))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "标题和内容不能为空" });
            return;
        }

        // 获取标签
        var tags = new List<string>();
        if (data.TryGetProperty("tags", out var tagsElement) && tagsElement.ValueKind == JsonValueKind.Array)
        {
            foreach (var tag in tagsElement.EnumerateArray())
            {
                if (tag.ValueKind == JsonValueKind.String)
                {
                    string? tagValue = tag.GetString();
                    if (!string.IsNullOrWhiteSpace(tagValue))
                    {
                        tags.Add(tagValue);
                    }
                }
            }
        }
        
        // 获取图片
        var images = new List<Dictionary<string, string>>();
        if (data.TryGetProperty("images", out var imagesElement) && imagesElement.ValueKind == JsonValueKind.Array)
        {
            foreach (var img in imagesElement.EnumerateArray())
            {
                if (img.ValueKind == JsonValueKind.Object)
                {
                    string? name = null;
                    string? imgData = null;
                    string? type = null;
                    
                    if (img.TryGetProperty("name", out var nameElement) && nameElement.ValueKind == JsonValueKind.String)
                    {
                        name = nameElement.GetString();
                    }
                    
                    if (img.TryGetProperty("data", out var dataElement) && dataElement.ValueKind == JsonValueKind.String)
                    {
                        imgData = dataElement.GetString();
                    }
                    
                    if (img.TryGetProperty("type", out var typeElement) && typeElement.ValueKind == JsonValueKind.String)
                    {
                        type = typeElement.GetString();
                    }
                    
                    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(imgData) && !string.IsNullOrEmpty(type))
                    {
                        images.Add(new Dictionary<string, string>
                        {
                            { "name", name },
                            { "data", imgData },
                            { "type", type }
                        });
                    }
                }
            }
        }

        // 获取当前用户ID
        int? userId = context.Session.GetInt32("UserId");
        
        // 创建帖子
        int postId;
        if (images.Count > 0)
        {
            // 使用带图片的方法
            postId = await forumService.CreatePostWithTagsAndImagesAsync(title, content, tags, images, userId);
        }
        else
        {
            // 使用原来的方法
            postId = await forumService.CreatePostWithTagsAsync(title, content, tags, userId);
        }

        // 返回结果
        context.Response.StatusCode = 201;
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { 
            id = postId,
            message = "帖子创建成功"
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"创建带标签的帖子API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "创建帖子失败" });
    }
});

// 论坛API：获取举报列表（管理员用）
app.MapGet("/api/admin/forum/reports", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 检查用户是否登录且是管理员
        int? userId = context.Session.GetInt32("UserId");
        bool isAdmin = context.Session.GetString("UserRole") == "admin";
        
        if (userId == null || !isAdmin)
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsJsonAsync(new { error = "无权限访问" });
            return;
        }

        // 获取查询参数
        string status = context.Request.Query["status"].ToString();
        if (string.IsNullOrEmpty(status)) status = "all";

        int page = 1;
        if (context.Request.Query.ContainsKey("page"))
        {
            int.TryParse(context.Request.Query["page"], out page);
            if (page < 1) page = 1;
        }

        int pageSize = 20;
        if (context.Request.Query.ContainsKey("pageSize"))
        {
            int.TryParse(context.Request.Query["pageSize"], out pageSize);
            if (pageSize < 1 || pageSize > 100) pageSize = 20;
        }

        // 获取举报列表
        var reports = await forumService.GetReportsAsync(status, page, pageSize);

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(reports);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取举报列表API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取举报列表失败" });
    }
});

// 论坛API：更新举报状态（管理员用）
app.MapPut("/api/admin/forum/reports/{id}", async (HttpContext context, ForumService forumService) =>
{
    try
    {
        // 检查用户是否登录且是管理员
        int? userId = context.Session.GetInt32("UserId");
        bool isAdmin = context.Session.GetString("UserRole") == "admin";
        
        if (userId == null || !isAdmin)
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsJsonAsync(new { error = "无权限访问" });
            return;
        }

        // 获取举报ID
        if (!int.TryParse(context.Request.RouteValues["id"]?.ToString(), out int reportId))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的举报ID" });
            return;
        }

        // 解析请求体
        var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        var data = JsonSerializer.Deserialize<Dictionary<string, string>>(requestBody, options);

        // 验证参数
        if (data == null || !data.ContainsKey("status") || string.IsNullOrEmpty(data["status"]))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "状态不能为空" });
            return;
        }

        string status = data["status"];
        if (status != "pending" && status != "resolved" && status != "rejected")
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "无效的状态值" });
            return;
        }

        // 更新举报状态
        bool success = await forumService.UpdateReportStatusAsync(reportId, status);

        if (!success)
        {
            context.Response.StatusCode = 404;
            await context.Response.WriteAsJsonAsync(new { error = "举报不存在" });
            return;
        }

        // 返回结果
        context.Response.ContentType = "application/json; charset=utf-8";
        await context.Response.WriteAsJsonAsync(new { message = "举报状态更新成功" });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"更新举报状态API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "更新举报状态失败" });
    }
});

// 测试文件系统权限
app.MapGet("/api/test/file-permissions", (ForumService forumService) =>
{
    try
    {
        forumService.TestFileSystemPermissions();
        return Results.Ok(new { message = "文件系统权限测试完成，请查看控制台日志" });
    }
    catch (Exception ex)
    {
        return Results.BadRequest(new { error = $"测试失败: {ex.Message}" });
    }
});

// 手动创建目录和测试文件
app.MapGet("/api/test/create-dirs", () =>
{
    try
    {
        string currentDir = Directory.GetCurrentDirectory();
        Console.WriteLine($"当前目录: {currentDir}");
        
        // 创建static目录
        string staticDir = Path.Combine(currentDir, "static");
        if (!Directory.Exists(staticDir))
        {
            Directory.CreateDirectory(staticDir);
            Console.WriteLine($"创建目录: {staticDir}");
        }
        else
        {
            Console.WriteLine($"目录已存在: {staticDir}");
        }
        
        // 创建uploads目录
        string uploadsDir = Path.Combine(staticDir, "uploads");
        if (!Directory.Exists(uploadsDir))
        {
            Directory.CreateDirectory(uploadsDir);
            Console.WriteLine($"创建目录: {uploadsDir}");
        }
        else
        {
            Console.WriteLine($"目录已存在: {uploadsDir}");
        }
        
        // 创建forum目录
        string forumDir = Path.Combine(uploadsDir, "forum");
        if (!Directory.Exists(forumDir))
        {
            Directory.CreateDirectory(forumDir);
            Console.WriteLine($"创建目录: {forumDir}");
        }
        else
        {
            Console.WriteLine($"目录已存在: {forumDir}");
        }
        
        // 创建测试文件
        string testFile = Path.Combine(forumDir, "test.txt");
        File.WriteAllText(testFile, "这是一个测试文件");
        Console.WriteLine($"创建测试文件: {testFile}");
        
        return Results.Ok(new { 
            message = "目录和测试文件创建成功", 
            currentDir = currentDir,
            staticDir = staticDir,
            uploadsDir = uploadsDir,
            forumDir = forumDir,
            testFile = testFile
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"创建目录或文件失败: {ex.Message}");
        return Results.BadRequest(new { error = $"创建失败: {ex.Message}" });
    }
});

// 测试上传页面
app.MapGet("/test/upload", async (HttpContext context) =>
{
    string filePath = Path.Combine(Directory.GetCurrentDirectory(), "templates", "test_upload.html");
    if (File.Exists(filePath))
    {
        string content = await File.ReadAllTextAsync(filePath);
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(content);
    }
    else
    {
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("测试页面不存在");
    }
});

// 论坛API：修复数据库表结构
app.MapGet("/api/admin/fix-database", async (HttpContext context) =>
{
    try
    {
        using (var connection = new MySql.Data.MySqlClient.MySqlConnection("Server=localhost;Port=3306;Database=findata;User=root;Password=root;"))
        {
            await connection.OpenAsync();
            
            // 检查forum_tags表是否存在count字段
            bool hasCountColumn = false;
            using (var cmd = new MySql.Data.MySqlClient.MySqlCommand(
                "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'findata' AND TABLE_NAME = 'forum_tags' AND COLUMN_NAME = 'count'", 
                connection))
            {
                var result = await cmd.ExecuteScalarAsync();
                hasCountColumn = Convert.ToInt32(result) > 0;
            }
            
            if (!hasCountColumn)
            {
                // 添加count字段
                using (var cmd = new MySql.Data.MySqlClient.MySqlCommand(
                    "ALTER TABLE forum_tags ADD COLUMN count INT DEFAULT 0", 
                    connection))
                {
                    await cmd.ExecuteNonQueryAsync();
                }
                
                // 更新现有标签的计数
                using (var cmd = new MySql.Data.MySqlClient.MySqlCommand(@"
                    UPDATE forum_tags t
                    SET count = (
                        SELECT COUNT(*) 
                        FROM forum_post_tags pt 
                        WHERE pt.tag_id = t.id
                    )", 
                    connection))
                {
                    await cmd.ExecuteNonQueryAsync();
                }
                
                await context.Response.WriteAsJsonAsync(new { 
                    success = true, 
                    message = "成功添加count字段并更新标签计数" 
                });
            }
            else
            {
                await context.Response.WriteAsJsonAsync(new { 
                    success = true, 
                    message = "count字段已存在" 
                });
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"修复数据库异常: {ex.Message}");
        Console.WriteLine($"异常堆栈: {ex.StackTrace}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { 
            success = false, 
            error = "修复数据库失败: " + ex.Message 
        });
    }
});

// 论坛按标签搜索页面路由
app.MapGet("/forum/search/tag/{tag}", async context =>
{
    try
    {
        // 获取标签参数
        var tag = context.Request.RouteValues["tag"]?.ToString();
        if (string.IsNullOrWhiteSpace(tag))
        {
            context.Response.Redirect("/forum");
            return;
        }

        // 返回搜索结果页面
        string htmlContent = await File.ReadAllTextAsync("templates/forum_list.html", Encoding.UTF8);
        
        // 在HTML中注入搜索标签信息
        htmlContent = htmlContent.Replace("<!--SEARCH_TAG_PLACEHOLDER-->", 
            $"<script>const searchTag = \"{tag}\";</script>");
        
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlContent, Encoding.UTF8);
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Error serving forum search by tag page");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("服务器内部错误，请稍后再试", Encoding.UTF8);
    }
});

// API：获取百度网盘链接
app.MapGet("/api/data/baidu-links/{type}", async (HttpContext context, DatabaseService dbService) =>
{
    try
    {
        // 获取链接类型
        string type = context.Request.RouteValues["type"]?.ToString();
        if (string.IsNullOrEmpty(type))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsJsonAsync(new { error = "链接类型不能为空" });
            return;
        }
        
        // 从数据库获取链接信息
        var link = await dbService.GetBaiduPanLinkByTypeAsync(type);
        
        // 如果找不到链接，返回默认值
        if (link == null)
        {
            // 默认链接信息
            var defaultLinks = new Dictionary<string, object>
            {
                ["stock"] = new {
                    fileName = "stock-trading-data.zip",
                    link = "https://pan.baidu.com/s/1Cpm_rgIZ8fbi1W8RqQAaMw?pwd=h5ne",
                    code = "h5ne"
                },
                ["index"] = new {
                    fileName = "stock-main-index-data.zip",
                    link = "https://pan.baidu.com/s/1I90UZIrkjgm7MfExkNtc1w?pwd=evax",
                    code = "evax"
                },
                ["financial"] = new {
                    fileName = "stock-fin-data-xbx.zip",
                    link = "https://pan.baidu.com/s/1E92yN-Y60dPDp5mT-ap-1Q?pwd=bgpw",
                    code = "bgpw"
                }
            };
            
            if (defaultLinks.ContainsKey(type))
            {
                await context.Response.WriteAsJsonAsync(defaultLinks[type]);
            }
            else
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsJsonAsync(new { error = "未找到指定类型的链接" });
            }
            return;
        }
        
        // 返回链接信息
        await context.Response.WriteAsJsonAsync(new
        {
            fileName = link.FileName,
            link = link.Link,
            code = link.Code
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取百度网盘链接API异常: {ex.Message}");
        context.Response.StatusCode = 500;
        await context.Response.WriteAsJsonAsync(new { error = "获取链接信息失败" });
    }
});

// 配置404页面
app.MapFallback(async context =>
{
    context.Response.StatusCode = 404;
    await context.Response.WriteAsync("页面未找到");
});

// 启动应用程序，监听8000端口
app.Urls.Add("http://localhost:8000");

// 启用控制器端点路由
app.MapControllers();

app.Run(); 